package com.innjia.utils;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import redis.clients.jedis.Jedis;

@Component
public class LockKeyUtil {
	
	
	/**
	 * 当从redis中获取获取数据为空的时候，尝试从redis中获取lockkey
	 * 
	 * @param key
	 * @return
	 */
	public static Boolean getLockKey(String key) {
		Jedis jedis = null;
		Boolean flag = false;
		key = key + "_" + "lockkey";
		 long distantTime = 30*1000;
		  
	        try {
	            jedis = RedisUtil.getJedis();
	            
	            Long result = jedis.setnx(key, (System.currentTimeMillis() + distantTime) + "");
	            if(result == 1) {
	            	//设置成功
	            	flag = true;
	            	return flag;
	            }else {
	            	//未设置成功
	            	 String oldExpireTime = jedis.get(key);
	 	            long oldTime = Long.parseLong(oldExpireTime);
	 	            if(oldTime <= System.currentTimeMillis()) {
	 	            	//锁已经超时,可以重新设置
	 	            	long now = System.currentTimeMillis();
	 	            	long newExpireTime = now + distantTime;
	 	            	String currentExpireTime = jedis.getSet(key, newExpireTime + "");
	 	            	if(StringUtils.equals(oldExpireTime, currentExpireTime)) {
	 	            		//如果设置新值时返回的旧值和刚开始拿到的旧值相等，说明这段时间这把锁没有别人动过
	 	            		flag = true;
	 	            		return flag;
	 	            	}else {
	 	            		//不相等，此时这把锁已经被其它人在使用，设置锁失败
	 	            		return flag;
	 	            	}
	 	            }else {
	 	            	//未超时，设置锁失败
	 	            	return flag;
	 	            }
	            }
	        } catch (Exception e) {
	            throw e;
	        } finally {
	            RedisUtil.releaseRedis(jedis);
	        }
	}
	
	/**
	 * 删除redis缓存中的lockKey
	 * 
	 */
	public static void delLockKey(String key) {
		Jedis jedis = null;
		key = key + "_" + "lockkey";
	        try {
	            jedis = RedisUtil.getJedis();
	            jedis.del(key);	            
	        } catch (Exception e) {
	            throw e;
	        } finally {
	            RedisUtil.releaseRedis(jedis);
	        }
	}
	
}
